package com.ido.alipay;

import com.alipay.api.*;
import com.alipay.api.domain.AlipayFundTransUniTransferModel;
import com.alipay.api.domain.Participant;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * Create by zoub
 * Date 2025/3/25 2:25 PM
 */
@Slf4j
@Component
public class AlipayFastClient {

    @Autowired(required = false)
    private AlipayClient alipayClient;

    /**
     * 发放支付宝单笔转账（单一固定商户,需优先初始化alipayClient）
     * https://opendocs.alipay.com/open/02byvi?pathHash=b367173b
     *
     * @return
     */
    public Boolean transfer(String bizNo, String identity, String identityType, String name, String amount, String remark, String orderTitle) {
        return transfer(bizNo, identity, identityType, name, amount, remark, orderTitle, null);
    }

    /**
     * 发放支付宝单笔转账(支持多商户分发场景)
     */
    public Boolean transfer(String bizNo, String identity, String identityType, String name, String amount, String remark, String orderTitle, AlipayConfig config) {
        log.info("【支付宝】发起转账,bizNo: {}, account: {}, name: {}, amount: {}, remark: {}, orderTitle: {}", bizNo, identity, name, amount, remark, orderTitle);
        try {
            AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
            AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
            // 设置商家侧唯一订单号
            model.setOutBizNo(bizNo);
            // 设置订单总金额
            model.setTransAmount(amount);
            // 设置描述特定的业务场景
            model.setBizScene("DIRECT_TRANSFER");
            // 设置业务产品码
            model.setProductCode("TRANS_ACCOUNT_NO_PWD");
            // 设置转账业务的标题
            model.setOrderTitle(orderTitle);
            // 设置收款方信息
            Participant payeeInfo = new Participant();
            payeeInfo.setIdentity(identity);
            payeeInfo.setIdentityType(identityType);
            payeeInfo.setName(name);
            model.setPayeeInfo(payeeInfo);
            // 设置业务备注
            model.setRemark(remark);
            // 设置转账业务请求的扩展参数
            model.setBusinessParams("{\"payer_show_name_use_alias\":\"true\"}");// 展示付款方别名

            request.setBizModel(model);
            AlipayClient alipayClient = null;
            if (Objects.isNull(config)) {
                alipayClient = this.alipayClient;
            } else {
                // 根据配置重新实例化alipayClient(应用多商户切换场景)
                alipayClient = init(config);
            }
            AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
            log.info("【支付宝】transfer response={}", response.getBody());
            if (response.isSuccess()) {
                log.info("【支付宝】转账成功!");
                return true;
            } else {
                log.info("【支付宝】转账失败!, error={}", response.getSubMsg());
                return false;
            }
        } catch (AlipayApiException e) {
            log.info("【支付宝】转账异常, e={}", e.getMessage());
            throw new RuntimeException(e);
        }
    }


    public AlipayClient init(AlipayConfig config) throws AlipayApiException {
        CertAlipayRequest alipayConfig = new CertAlipayRequest();
        alipayConfig.setAppId(config.getAppId());// appid
        alipayConfig.setPrivateKey(config.getPrivateKey());  // 应用秘钥
        alipayConfig.setEncryptor(config.getEncryptKey());
        alipayConfig.setServerUrl(config.getServerUrl());
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        alipayConfig.setFormat("json");
//        alipayConfig.setCertContent("<-- 请填写您的应用公钥证书内容字符串 -->");
//        alipayConfig.setAlipayPublicCertContent("<-- 请填写您的支付宝公钥证书内容字符串 -->");
//        alipayConfig.setRootCertContent("<-- 请填写您的支付宝根证书内容字符串 -->");
        // 如果不使用content的模式,那么这里需要自行设置文件的绝对路径
        String serverPath = this.getClass().getResource("/").getPath();
        alipayConfig.setCertPath(serverPath + config.getAppCertPath());
        alipayConfig.setAlipayPublicCertPath(serverPath + config.getAlipayPublicCertPath());
        alipayConfig.setRootCertPath(serverPath + config.getRootCertPath());
        return new DefaultAlipayClient(alipayConfig);
    }

}
